// heartrate.js
var iconUrl = require('../../config.js').iconUrl;
var blu=require('../../utils/blue.js');
var cmds = require('../../utils/cmd.js');
var waveHelper=require("./wave.js");
Page({

  /**
   * 页面的初始数据
   */
  data: { 
    iconUrl:iconUrl,
    borderW:0,
    borderH:0,
    waveW:0,
    waveH: 0,
    
    wave:'',
    max_heart:0,//最大心率
    min_heart:0,//最小心率
    current_heart:0,//当前心率
     
     level_1:0,//热身时间
     level_2: 0,//燃脂时间
     level_3: 0,//唐源消耗
     level_4: 0,//乳酸堆积
     level_5: 0,//极限运动
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    var w = getApp().globalData.screenW;
    var h = getApp().globalData.screenH;
    
    var canvasW = w * 0.63
    this.setData({
      waveW: canvasW,
      waveH: canvasW,
      borderW: canvasW * 0.37,
      borderH: canvasW,      
    })
    var wave = waveHelper.wave('wave', canvasW, canvasW);
    wave.start(canvasW);
    this.setData({ wave: wave });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // var that = this;
    // //打开心率检测
    // blu.blue_write(cmds.set6_1());
    // // 定时获取数据
    // var interval1 = setInterval(function () {
    //   that.heartbeat();
    // }, 2000);
    // wx.setStorageSync("interval1", interval1);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    //打开心率检测
    blu.blue_write(cmds.set6_1());
    // 定时获取数据
    var interval1 = setInterval(function () {      
      that.heartbeat();
    }, 1000);
    var wave = this.data.wave;
    wave.start();
    wx.setStorageSync("interval1", interval1);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {    
          
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {  
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  //发送心跳包
  heartbeat:function(){
    blu.blue_write(cmds.set6_2());
    var that=this;
    setTimeout(function(){
      var rate = wx.getStorageSync("bracelet_data.current_heart_rate"); 
      var max_heart = rate > that.data.max_heart ? rate : that.data.max_heart;
      var min_heart = rate < that.data.mix_heart ? rate : that.data.mix_heart;
      that.setData({
        max_heart: max_heart,//最大心率
        min_heart: min_heart,//最小心率
        current_heart: rate,//当前心率        
      });
      that.data.wave.step(rate/100);      
    },100);
  },   
})